<template>
  <div class="downloadFile">
    <div
      class="dialog animated"
      :class="open? 'fadeIn':'fadeOut'"
      v-show="show"
      :style="{visibility: (visible?'visible':'hidden')}"
    >
      <div class="panel animated" :class="open? 'zoomIn':''">
        <div class="title">
          正在下载
          <div class="close" @click="cancel()"></div>
        </div>
        <div style="padding-bottom:0.5rem;">
          <table class="table" cellspacing="0">
            <thead class="thead">
              <tr>
                <td style="width: 4rem;">文件名称</td>
                <td style="width: 4rem;">文件大小</td>
                <td style="width: 6rem;">下载进度</td>
                <td style="width: 4rem;">操作</td>
              </tr>
            </thead>
            <tbody class="tbody">
              <tr v-for="item,index in fileList">
                <td>
                  <!-- <el-checkbox v-model="item.checked"></el-checkbox> -->
                  {{item.name}}{{item.fileType}}
                </td>
                <td>{{item.size}}</td>
                <td>
                  <el-progress
                    :text-inside="true"
                    :stroke-width="20"
                    :percentage="item.downloadProgress"
                    :color="item.dowmloadStatus"
                  ></el-progress>
                </td>
                <td>
                  <span
                    class="operate_btn"
                    v-if="item.dowmloadStatus == '#F56C6C'"
                    @click="handleStart(index,item)"
                  >重新下载</span>
                  <span class="operate_btn" v-if="item.isStart" @click="handleStart(index,item)">开始</span>
                  <span class="operate_btn" @click="handleDelete(index,item)">删除</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
var vm, user;
export default {
  data: function() {
    return {
      show: false,
      open: false,
      visible: false,
      fileList: []
    };
  },
  methods: {
    init: function(data) {
      vm.show = true;
      setTimeout(function() {
        vm.open = true;
        vm.visible = true;
      }, 11);
      console.log(data);
      vm.fileList = data;
      user = tool.getItem(lsKey.user, true);
      vm.fileList.forEach(item => {
        item.req = null;
        item.downloadProgress = 0;
        item.dowmloadStatus = item.downLoadPath == null ? "#F56C6C" : "#409EFF";
        item.checked = false;
        item.isStart = true;
        vm.setFileSize(item);
      });
    },
    setFileSize : function(item) {
				var size = item.size;
				//size单位是KB
				if(size > 1024*1024) {
					//大于1G,单位设成GB
					size = (size / (1024 * 1024)).toFixed(2) +"GB";
				}else if(size > 1024) {
					//大于1M,单位设成MB
					size = (size / 1024).toFixed(2) +"MB";
				}else {
					size = size + "KB";
				}
				item.size = size;
			},
    sure: function() {
      vm.$emit("callback", "新增成功");
      vm.cancel();
    },
    cancel: function() {
      //隐藏弹窗
      vm.open = false;
      vm.abortReq();
      setTimeout(function() {
        vm.show = false;
        vm.visible = false;
        vm.fileList = [];
      }, 500);
    },
    abortReq(){
      for(let i = 0;i<vm.fileList.length;i++){
        if(vm.fileList[i].req != null && vm.fileList[i].dowmloadStatus == "#409EFF"){
          vm.fileList[i].req.abort();
        }
      }
    },
    downloadFile(item) {
      var req = new XMLHttpRequest();
      req.open("get", item.downLoadPath, true);
      //监听进度事件
      req.addEventListener(
        "progress",
        function(evt) {
          if (evt.lengthComputable) {
            var percentComplete = evt.loaded / evt.total;
            item.downloadProgress = parseInt(percentComplete * 100);
            console.log(item.downloadProgress);
            if (item.downloadProgress == 100) {
              item.dowmloadStatus = "#67C23A";
              
            }
            vm.$forceUpdate();
            // $("#progressing").html((percentComplete * 100) + "%");
          }
        },
        false
      );
      req.addEventListener(
        "error",
        function(evt) {
          item.dowmloadStatus = "#F56C6C";
          vm.$forceUpdate();
        },
        false
      );
      req.addEventListener(
        "abort",
        function(evt) {
          item.dowmloadStatus = "#E6A23C";
          vm.$forceUpdate();
        },
        false
      );
      req.responseType = "blob";
      req.onreadystatechange = function() {
        if (req.readyState === 4 && req.status === 200) {
          var filename = item.name;
          if (typeof window.chrome !== "undefined") {
            // Chrome version
            var link = document.createElement("a");
            link.href = window.URL.createObjectURL(req.response);
            link.download = filename;
            link.click();
          } else if (typeof window.navigator.msSaveBlob !== "undefined") {
            // IE version
            var blob = new Blob([req.response], {
              type: "application/force-download"
            });
            window.navigator.msSaveBlob(blob, filename);
          } else {
            // Firefox version
            var file = new File([req.response], filename, {
              type: "application/force-download"
            });
            window.open(URL.createObjectURL(file));
          }
        }
      };
      item.req = req;
      req.send();
    },
    handleStart(index, item) {
      item.isStart = false;
      if (item.downLoadPath != null) {
        vm.downloadFile(item);
      } else {
        tool.message({
          showClose: true,
          message: "资源异常,暂无法下载!",
          type: "error"
        });
      }
    },
    handleDelete(index, item) {
      vm.fileList.splice(index, 1);
    }
  },
  created: function() {
    vm = this;
  }
};
</script>
<style lang="scss">
.downloadFile {
  .el-form-item__label {
    font-size: 0.16rem;
    color: #666666;
  }
  .el-checkbox__label {
    font-size: 0.16rem;
    color: #666666;
  }
  .operate_btn {
    font-size: 0.16rem;
    color: #2e83f6;
    cursor: pointer;
    user-select: none;
  }
}
</style>
<style scoped src="@/style/module/table.css"></style>
<style scoped src="@/style/module/dialog.css"></style>
<style scoped>
</style>


